﻿jQuery(function ($) {
	$('ul.thumbnails-block li').not($('a[data-hash="new"]').parent()).click(function (e) {
		e.preventDefault();

		var $li = $(this);

		if ($li.is('.active'))
			return;

		var hash = $('a[data-hash]', $li).data('hash');

		updateActiveThumbnail(hash);
		updateBook(hash);
	});

	$('#next').add('#prev').click(function (e) {
		e.preventDefault();

		var $a = $(this);

		var $books = $('div.book-content');

		var index = $books.index($books.not(':hidden'));
		var count = $books.length;

		switch ($a.attr('id')) {
			case 'next':
				index = index < count - 1 ? index + 1 : 0;
				break;
			case 'prev':
				index = index <= 0 ? count - 1 : index - 1;
				break;
			default:
				break;
		}

		$('div.book-content').not(':hidden').hide().end().eq(index).show();
		


		recalcScroll();

		updateActiveThumbnail($('div.book-content').not(':hidden').data('hash'));
	});

	function updateBook(hash) {
		$('div.book-content').not(':hidden').hide().end().filter('[data-hash="' + hash + '"]').show();
		recalcScroll();
	}

	function updateActiveThumbnail(hash) {
		$('ul.thumbnails-block li.active').removeClass('active');

		$('ul.thumbnails-block a[data-hash="' + hash + '"]').each(function () {
			$(this).closest('li').addClass('active');
		});

	}
	function recalcScroll() {
		var $scrolls = $('div.toc').add($('div.description'));
		$scrolls.has(':hidden').getNiceScroll().hide();
		$scrolls.not(':hidden').getNiceScroll().show();
	}

	function init() {
		$('div.description').each(function () {
			var $this = $(this);
			var $page = $this.parents('.book-content').clone(false).css({ display: 'block', visibility: 'hidden' });

			$('body').append($page);

			var h = 369 - $('div.book-column .wrapper', $page).height();
			$page.remove();

			$this.height(h);
		});

		$('div.toc').add($('div.description')).niceScroll({
			cursorcolor: '#B86030',
			cursorfixedheight: 100,
			zindex: 10,
			touchbehavior: false,
			autohidemode: false,
			boxzoom: false,
		});

		recalcScroll();
	}

	init();
});